import { _decorator, Component, math, Node, RigidBody, Vec3 } from 'cc';
import { Actor } from './Actor';
import { VirtualInput } from '../VirtualInput';
import { MathUtil } from '../MathUtil';
import { UtilTmp } from '../util';
const { ccclass, property } = _decorator;

@ccclass('MoveController')
export class MoveController extends Component {

    @property({ type: Actor })
    player: Actor;

    @property(Node)
    planeRoot: Node | null = null;

    // 目标位置
    private targetPos: Vec3 = new Vec3();

    // 移动参数
    private destForward: Vec3 = new Vec3();

    protected onLoad(): void {
        this.targetPos = this.player.node.position.clone();
    }

    start() {
        // player
    }

    update(deltaTime: number) {
        // if (this.actor.currState != StateDefine.Run) {
        //     return;
        // }
        const len = this.handleInput();
        if (len > 0.1) {
            this.walk();
        } else {
            // 自动寻怪物
            // let enemy = this.getNeareastEnemy()
            // if (enemy) {
            //     Vec3.subtract(this.actor.destForward, enemy.worldPosition, this.node.worldPosition);
            //     this.actor.destForward.normalize()

            //     // 如果有射击
            //     this.actor.changeState(StateDefine.Attack);
            // }
        }
        this.player.node.setPosition(this.targetPos);
    }

    private handleInput(): number {
        let x = VirtualInput.horizontal;
        let y = VirtualInput.vertical;

        this.destForward.x = x;
        this.destForward.z = -y;
        this.destForward.y = 0;
        this.destForward.normalize();
        return this.destForward.length();
    }

    private walk() {
        let speed = this.player.moveSpeed * this.destForward.length();
        UtilTmp.V3_0.x = math.clamp(this.destForward.x, -1, 1) * speed;
        UtilTmp.V3_0.z = math.clamp(this.destForward.z, -1, 1) * speed;
        // console.log(UtilTmp.V3_0)
        this.targetPos.x += UtilTmp.V3_0.x;
        this.targetPos.z += UtilTmp.V3_0.z;

        // planeRoot
        if (this.planeRoot) {
            UtilTmp.V3_1.x = this.planeRoot.position.x;
            UtilTmp.V3_1.z = this.planeRoot.position.z;
            UtilTmp.V3_1.x -= UtilTmp.V3_0.x * 0.5;
            UtilTmp.V3_1.z -= UtilTmp.V3_0.z * 0.5;
            this.planeRoot.setPosition(UtilTmp.V3_1);
        }

    }
}


